package com.hmdp.Intecepter;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.hmdp.dto.UserDTO;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.LOGIN_USER_KEY;
import static com.hmdp.utils.RedisConstants.LOGIN_USER_TTL;

/**
 * @author zkx
 */
@Slf4j
public class ReflushIntereptor  implements HandlerInterceptor {
    public ReflushIntereptor(StringRedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    private StringRedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("authorization");
        log.warn("token={}",token);
        //在authorization
        //字段不为空
        if(StrUtil.isBlankIfStr(token)){
            //返回401，表示未授权
            //response.setStatus(401);
            return true;
        }
        //2、基于token获取身份
        String loginUserInfo = LOGIN_USER_KEY + token;
        Map<Object, Object> userMap = redisTemplate.opsForHash().entries(loginUserInfo);
        //没有查到信息
        if(userMap.isEmpty()){
            //返回401，表示未授权
            //response.setStatus(401);
            return true;
        }
        UserDTO userDTO = BeanUtil.fillBeanWithMap(userMap, new UserDTO(), false);
        //放入线程池中TreadLocal
        UserHolder.saveUser(userDTO);
        //刷新有效时间
        redisTemplate.expire(loginUserInfo,LOGIN_USER_TTL, TimeUnit.MINUTES);
        //放行
        return true;
    }
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserHolder.removeUser();
    }
}
